#include "../include/head.h"
#include "../include/threadPool.h"

/* Usage*/
void* threadFunc(void * arg)
{ 
    threadPool_t *pthreadPool = (threadPool_t *)arg;
    while(1)
    {
        //工人线程 后出队 消费者
        pthread_mutex_lock(&pthreadPool->mutex);
        while(pthreadPool->taskQueue.size == 0 && pthreadPool->exitFlag == 0)
        {
              pthread_cond_wait(&pthreadPool->cond,&pthreadPool->mutex);
        }
        //检查退出状态
        if(pthreadPool->exitFlag == 1)
        { 
            printf("i am worker,i am going to exit!\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            pthread_exit(NULL);
        }
        if(pthreadPool->taskQueue.phead == NULL)
        { 
            printf("taskQueue phead is NULL\n");
            pthread_mutex_unlock(&pthreadPool->mutex);
            continue;
        }
        int netfd = pthreadPool->taskQueue.phead->netfd;
        printf("i am worker,netfd = %d\n",netfd);
        head_dele(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->mutex);

        uid_t uid;
        int login_res = login(netfd,&uid);
        if(login_res <= 0)
        { 
            printf("login failed,res = %d\n",login_res);
            continue;
        }

        // 申请当前工作目录的栈空间
        commandStack_t curPathStack;
        init_command_stack(&curPathStack);
        // 将/home/user/zhangsan压入栈中
        char homeDir[1024] = {0};
        //get_homedir(homeDir);
        struct passwd *pwd = getpwuid(uid);
        strcpy(homeDir, "/home/");
        strcat(homeDir, pwd->pw_name);
        strcat(homeDir, "/zhangsan");
        printf("homeDir = %s\n", homeDir);
        push_command_stack(&curPathStack, homeDir, strlen(homeDir));
        /* printf("查看curPathStack是否正确:"); */
        /* print_stack(&curPathStack); */
        // 解析命令
        while(1){
            recvCommand(netfd, &curPathStack);
        }
            close(netfd);
    }
    return 0;
    
}


int makeWorker(threadPool_t *pthreadPool)
  {
      for(int i = 0;i<pthreadPool->workerArr.workernum;i++)
      {
          pthread_create(&pthreadPool->workerArr.tidArr[i],NULL,threadFunc,pthreadPool);
      }
      return 0;
  }
